var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var session = require('express-session');
var nedbStore = require('nedb-session-store')(session);
var logger = require("morgan");

var indexRouter = require("./routes/index");
var loginRouter = require("./routes/login");
var registeredRouter = require("./routes/registered");
var usersRouter = require("./routes/users");

var app = express();

app.use(logger("dev"));
app.use(express.json());
app.use(
  express.urlencoded({
    extended: false
  })
);
app.use(cookieParser());
// 使用 session 中间件，保存session信息
app.use(session({
  secret: 'mySession', // 对session id 相关的cookie 进行签名
  resave: true,
  saveUninitialized: false, // 是否保存未初始化的会话
  cookie: {
    path: '/',
    maxAge: 24 * 60 * 60 * 1000, // 设置 session 的有效时间，单位毫秒
  },
  store: new nedbStore({
    filename: 'session.db'
  })
}));
app.use(express.static(path.join(__dirname, "public")));

//登录拦截器，必须放在静态资源声明之后、路由导航之前
app.use(function (req, res, next) {
  var url = req.originalUrl;
  var userName = req.session.userName;
  if (!userName && url !== "/login" && url !== "/registered") {
    return res.send({
      status: 202,
      msg: '用户未登录',
      data: {}
    });
  }
  next();
});
app.use("/", indexRouter);
app.use("/login", loginRouter);
app.use("/registered", registeredRouter);
app.use("/users", usersRouter);

module.exports = app;